/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.op.mr3;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

import com.op.lib.JSActivity;
import com.op.lib.Protocal;

public class GameActivity extends JSActivity implements Handler.Callback {

    static {
        System.loadLibrary("gnustl_shared");
        System.loadLibrary("game");
    }

    private static final String USER_NAME = "Mr.3";

    protected Handler           mHandler;

    private Protocal            mProtocal;

    private AdmobAdapter        mAdmob;

    // ------------ user hold the progress of back press
    private boolean             mBackHandled;

    private String              mBLockMessage;

    @Override
    protected void initialize() {
        mProtocal = new Protocal(ProtocalIDs.MESSAGE_TYPE, ProtocalIDs.MESSAGE_DATA);
        mProtocal.put(ProtocalIDs.ID_SHARE, "share");
        mProtocal.put(ProtocalIDs.ID_NAMEINPUT, "nameinput");
        mProtocal.put(ProtocalIDs.ID_NAMECHANGED, "namechanged");
        mProtocal.put(ProtocalIDs.ID_NAMECANCELED, "namecanceled");
        mProtocal.put(ProtocalIDs.ID_ADMOB, "admob");
        mProtocal.put(ProtocalIDs.ID_UI_BACK_CLICK, "backclick");
        mProtocal.put(ProtocalIDs.ID_UI_HANDLEBACK, "handleback");

        mBackHandled = false;
        try {
            mBLockMessage = mProtocal.createMessage(ProtocalIDs.ID_UI_BACK_CLICK).toString();
        } catch (Exception e) {
        }

        this.mHandler = new Handler(this);
    }

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // bind glSurfaceView
        setContentView(mView);

        // add AdView
        mAdmob = new AdmobAdapter(this);
        FacebookLoginActivity.init(this);
    }

    // ======================
    // user handle backpress
    // ======================
    @Override
    public void onBackPressed() {
        if (mBackHandled) {
            processRequest(mBLockMessage);
            return;
        }
        super.onBackPressed();
    }

    private void handleBackPress(JSONObject obj) {
        mBackHandled = obj.optBoolean("enable", false);
    }

    // ======================
    // handle native message
    // ======================
    @Override
    public Object receiveMessage(JSONObject op) throws JSONException {
        //System.out.println("GameActivity.receiveMessage():" + op.toString());
        Object result = null;
        int id = mProtocal.id(op);
        if (id != -1) {
            handleLocally(id, op.opt(ProtocalIDs.MESSAGE_DATA));
        } else {
            result = new JSONObject("{\"exception\":\"operation not found\"}");
        }
        return result;
    }

    public void sendMessageAsyn(String operation) {
        handleLocally(ProtocalIDs.SEND_MESSAGE, operation);
    }

    public void sendMessage(String msg) {
        processRequest(msg);
    }

    public void sendMessage(JSONObject msg) {
        processRequest(msg.toString());
    }

    // ======================
    // process message within main thread
    // ======================
    private void handleLocally(int id, Object obj) {
        this.mHandler.sendMessage(this.mHandler.obtainMessage(id, obj));
    }

    @Override
    public boolean handleMessage(Message msg) {
        //System.out.println("GameActivity.handleMessage():" + (msg.obj == null ? "_empty_" : msg.obj.toString()));
        switch (msg.what) {
            case ProtocalIDs.SEND_MESSAGE:
                processRequest((String) msg.obj);
                break;
            case ProtocalIDs.ID_NAMEINPUT:
                showInputDialog();
                break;
            case ProtocalIDs.ID_SHARE:
                startSharing();
                break;
            case ProtocalIDs.ID_ADMOB:
                mAdmob.updateStatus((JSONObject) msg.obj);
                //mView.invalidate();
                break;
            case ProtocalIDs.ID_UI_HANDLEBACK:
                this.handleBackPress((JSONObject) msg.obj);
                break;
        }
        return true;
    }

    private void startSharing() {
        FacebookLoginActivity.startSharing(this, null);
    }

    private void showInputDialog() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        InputNameDialog newFragment = InputNameDialog.newInstance();
        newFragment.show(ft, "dialog");
    }

    public void cancelInput() {
        try {
            JSONObject msg = mProtocal.createMessage(ProtocalIDs.ID_NAMECANCELED);
            sendMessage(msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void finishInput(String string) {
        if (string == null) {
            string = USER_NAME;
        }
        try {
            JSONObject msg = mProtocal.createMessage(ProtocalIDs.ID_NAMECHANGED, new JSONObject().put("name", string));
            sendMessage(msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
